define([
	"jquery",
	"bbcare",
	"bootstrap",
	"template",
	"oms_config/root",
	"oms_tpl/application.tpl",
	"oms_model/account",
	"ac/app/applicationCache",
	"ac/app/uploadOfflineData.servers"],
function($,$bb,$bootstrap,$template,$root,tpl_app,Account,$applicationCache,$servers){
	var uploadOfflineData = {};
	var defaults;
	
	/**
	 * 获取当前登录的账号信息
	 */
	var getCurrUser = function(){
		var account = $bb.getSessionStorage("account");
		if(account==null){
			window.location.href = "login.html?code=301";
		}else{
			account = eval("("+account+")");
			account = new Account(account);
		}
		return account;
	}
	
	/**
	 * 切换到选中的APP
	 */
	var onAppSelect = function(){
		var id =  $(this).attr("data-id");
		$bb.get("auth/app/switch?appId="+id,function(ret){
			if(ret&&ret.success){
				var account = new Account(ret.data);
				defaults.account = account;
				$bb.setSessionStorage("account",JSON.stringify(ret.data));
				initUI();
				setSession();
			}
		});
	}
	
	/**
	 * 初始化全局UI
	 */
	var initUI = function(){
		//初始化用户名称
		$("#oms_account_name").text(defaults.account.alias);
		//初始化最小化导航栏事件
		$(".sidebar-toggle").click(onToggleNavbar);
		//初始化登出事件
		$("#logout").click(onLogout);
		//初始化当前账号菜单栏
		$('.dropdown-toggle').dropdown();
		//初始化应用列表
		tpl_app.init('bb-tenant');
		$('#bb-tenant').html($template("tpl_application_dropdown",{apps:defaults.account.apps}));
		$('#accountApps a').click(onAppSelect);
		$('.dropdown-toggle').dropdown();
	}
	
	/**
	 * 最小化(恢复)导航栏
	 */
	var onToggleNavbar = function(){
		$("#bb-tenant").toggleClass("mini");
		$(".sidebar-lc").toggleClass("mini");
		$("#content").toggleClass("max");
	}
	
	/**
	 * 退出系统处理
	 */
	var onLogout = function(){
		var config = $root.init();
		window.location.href = config.route.login;
	}
	
	/**
	 * 设置Session
	 */
	var setSession = function(){
		$bb.setSessionStorage("sessionId",defaults.account.sessionID);
		$bb.setSessionStorage("sessionTime",new Date().getTime());
	}

	/**
	 * 跳转到home页面
	 */
	var gotoHome = function(){
		window.location.href = "home.html";
	}

	/**
	 * template模板
	 */
	var uploadOffflineTpl = function(){
		return 	'<script id="tpl_upload_offfline" type="text/html">'+
				'	<div class="upload-offline-tip">{{tip}}</div>'+
				'	<div class="progress">'+
				'	  	<div class="progress-bar" role="progressbar" aria-valuenow="{{percentage}}" aria-valuemin="0" aria-valuemax="100" style="width: {{percentage}}%;"></div>'+
				'	</div>'+
				'	<p class="upload-offline-reminder">{{reminder}}</p>'+
				'</script>';
	}

	/**
	 * 处理数据
	 */
	var handle = function(cacheSave,i,total){
		var data = {};
		data.tip = "正在上传离线数据("+ ( total - i ) +"/"+ total +")";
		if( cacheSave[i].info.type == 2 ){
			data.reminder = "当前正在上传图片";
		}else{
			data.reminder = "当前正在上传"+ cacheSave[i].info.patientName +"的"+ cacheSave[i].info.queueName + cacheSave[i].info.taskName +"数据";
		}
		data.percentage = parseInt( ( total-i ) / total * 100 );
		return data;
	}

	/**
	 * 请求提交（建档和门诊任务）后的回调函数
	 */
	var ajaxSubmitCallBack = function(data,cacheSave,i,total){
		if(!data.success){
			if( cacheSave[i].info.type == 0 ){
				$bb.toastShow(data.msg ? data.msg : "建档出错！");
			}else if( cacheSave[i].info.type == 1 ){
				$bb.toastShow(data.msg ? data.msg : "门诊任务提交出错！");
			}else if( cacheSave[i].info.type == 2 ){
				$bb.toastShow(data.msg ? data.msg : "上传图片出错！");
			}
		}else{
			cacheSave.splice(i,1);
		}
		$bb.setIocalStorage("cacheSave",JSON.stringify(cacheSave));
		i--;
		if(i >= 0){
			ajaxSubmit(cacheSave,i,total);
		}else{
			setTimeout(gotoHome,3000)
		}
	}

	/**
	 * 请求提交（建档和门诊任务）
	 */
	var ajaxSubmit = function(cacheSave,i,total){
		$("#uploadOffline").html(uploadOffflineTpl());
		$("#uploadOffline").html($template("tpl_upload_offfline",handle(cacheSave,i,total)));
		if( cacheSave[i].info.type == 0 ){		//  门诊建档
			$servers.ajaxPatientAddNew(cacheSave,i,total,ajaxSubmitCallBack);
		}else if( cacheSave[i].info.type == 1 ){ // 门诊任务
			$servers.ajaxSubmitOfflineTaskCont(cacheSave,i,total,ajaxSubmitCallBack);
		}else if( cacheSave[i].info.type == 2 ){ // 上传图片
			$servers.ajaxUploadMultiFile(cacheSave,i,total,ajaxSubmitCallBack);
		}
	}

	/**
	 * 排序
	 */
	var sortCacheSave = function(cacheSave){
		var sortArr = [];
		var arrType2 = []; // 上传图片
		var arrType0 = []; // 门诊建档 
		var arrType1 = []; // 门诊任务
		for (var i = 0; i < cacheSave.length; i++) {
			if( cacheSave[i].info.type == 0 ){
				arrType0.push(cacheSave[i]);
			}else if( cacheSave[i].info.type == 1 ){
				arrType1.push(cacheSave[i]);
			}else if( cacheSave[i].info.type == 2 ){
				arrType2.push(cacheSave[i]);
			}
		}
		// 上传顺序是：2:图片、0:建档、1、门诊任务（倒序上传，所以应该是1、0、2）
		sortArr = arrType1.concat( arrType0, arrType2 );
		return sortArr;
	}

	/**
	 * 离线上传UI
	 */
	var uploadOfflineUI = function(){
		$(".upload-offline .btn-bbcare").click(gotoHome);
		if( $bb.getIocalStorage("cacheSave") )
		var cacheSave = JSON.parse( $bb.getIocalStorage("cacheSave") );
		if( cacheSave && cacheSave.length > 0 ){
			cacheSave = sortCacheSave(cacheSave);
			var total = cacheSave.length;
			var i = cacheSave.length-1;
			ajaxSubmit(cacheSave,i,total);
		}else{
			gotoHome();
		}
	}

	uploadOfflineData.init = function(){
		defaults = {
			account:getCurrUser()
		};
		initUI();
		setSession();
		uploadOfflineUI();
		$applicationCache.init(); // 离线
	}

	return uploadOfflineData;
});